package com.tfswue.jqr.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
//开启websecurity配置
@EnableWebSecurity
public class SecurityConfig {
    //配置密码加密器（必需）
    @Bean
    public BCryptPasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();  //使用BCrypt 强哈希加密
    }

    //配置用户存储（内存方式，生产环境需要连接数据库）
    @Bean
    public UserDetailsService userDetailsService(){
        UserDetails user = User.builder()
                .username("user")
                .password(passwordEncoder().encode("pass"))  //密码必须加密
                .roles("USER") //分配角色
                .build();

        UserDetails admin = User.builder()
                .username("admin")
                .password(passwordEncoder().encode("admin"))
                .roles("ADMIN","USER")  //可分配多个角色
                .build();

        return new InMemoryUserDetailsManager(user,admin); //存储在内存中
    }

    //核心安全配置（Http请求过滤规则）
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception{
        http
                .authorizeHttpRequests(authorize -> authorize
                        .requestMatchers("/","/index").permitAll()     //允许根路径匿名访问
                        .requestMatchers("/public/**").permitAll()       //公共路径无需验证
                        .requestMatchers("/admin/**").hasRole("ADMIN")  //仅管理员可访问
                        .requestMatchers("/api/**").hasAnyRole("USER")
                        .anyRequest().authenticated()   //其他路径需要验证
                )
                .formLogin(form -> form
                        .loginPage("/index.html")   //与实际文件路径一致
                        .loginProcessingUrl("/login") //处理登录的URL
                        .defaultSuccessUrl("/public/hello") //登录成功后跳转到此路径
                        .permitAll()

                )
                .logout(logout -> logout
                        .logoutSuccessUrl("/public/goodbye") //登出后跳转地址
                        .permitAll()
                )

                .csrf(csrf -> csrf
                        .disable());     //禁用CSRF保护（开发环境方便测试）


        return http.build();

    }
}